package com.shengdong.water.feature.login



import android.annotation.SuppressLint
import android.content.Intent
import android.util.Log
import androidx.activity.OnBackPressedCallback
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route

import com.hjq.toast.Toaster
import com.kongzue.dialogx.dialogs.WaitDialog
import com.shengdong.water.R

import com.shengdong.water.base.BaseVMActivity
import com.shengdong.water.base.UiState
import com.shengdong.water.code.config.RouterConfig
import com.shengdong.water.code.config.UserConfig
import com.shengdong.water.code.router.RouterManager

import com.shengdong.water.databinding.ActivityLoginBinding
import com.shengdong.water.code.utils.DataStoreUtil.gson
import com.shengdong.water.code.utils.dataStore
import com.shengdong.water.code.viewmodel.LoginViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RouterConfig.LOGIN_PATH)
@AndroidEntryPoint
class LoginActivity: BaseVMActivity<ActivityLoginBinding, LoginViewModel>() {

//    @Autowired
//    @JvmField
//    var REDIRECT_PATH: String? = null // 登录成功后重定向的路径

    override fun showTitleBar() = false


    override fun getViewModelClass() = LoginViewModel::class.java
    override fun getLayoutId() = R.layout.activity_login
    // 是否显示状态栏
    override fun showStatusBar() = false


    override fun initViews() {
//        RouterManager.inject(this)
        binding.viewModel = viewModel

        // 设置登录按钮点击事件
        binding.btnLogin.setOnClickListener {
//            RouterManager.navigate(RouterConfig.MAIN_PATH)
//            finish()
            if(viewModel.account.get().isNullOrEmpty()){
                showToast("输入的账号不能为空")
                return@setOnClickListener
            }
            if(viewModel.password.get().isNullOrEmpty()){
                showToast("输入的密码不能为空")
                return@setOnClickListener
            }
            viewModel.login()
        }
    }

    override fun initData() {
        // 初始化数据
    }
    
    override fun observeData() {
        // 观察 ViewModel 中的数据变化
        lifecycleScope.launch {
            viewModel.userToken.collect { user ->
                user?.let {
                    Log.d("LoginActivity", "Saving user token: ${user.accessToken}")
                    //保存用户信息
                    dataStore.edit { preference ->
                        preference[stringPreferencesKey("access_token")] = user.accessToken
                        preference[stringPreferencesKey("user_info")] = gson.toJson(user)
                    }
                    navigateToNextPage()
                }
            }
//            viewModel.userToken.observe(this@LoginActivity) { user ->
//                Log.e("获取认证","user"+user)
//            }
        }
    }

    override fun showLoading(loading: String) {
        WaitDialog.show(loading)
    }

    override fun dismissLoading() {
        WaitDialog.dismiss()
    }


    override fun showToast(message: String) {
        Toaster.show(message)
    }

    override fun showError(message: String) {
//        toast(message)
        Toaster.show(message)
    }


    // 跳转到下一个页面
    private fun navigateToNextPage() {
        RouterManager.navigate(RouterConfig.MAIN_PATH)
        finish()
    }

    // 处理返回键事件
    @SuppressLint("SuspiciousIndentation")
    override fun handleBackPress() {// 检查是否来自401未授权跳转
    val from401 = intent.getBooleanExtra("FROM_401", false)
        if (from401) {
            // 如果来自401未授权跳转，则拦截返回键，直接退出应用
            // 退出应用
            finishAffinity()
        }
    }
}